package dao

import (
	"errors"
	"fmt"
)

//init
func (u *AdminUser) init() {
	if Db == nil {
		InitMysql()
	}
}

//登录校验
func (u *AdminUser) CheckLogin(userName, userPass string) (err error) {
	if userName == "" || userPass == "" {
		err = errors.New("用户名或密码错误")
		return
	}

	//转换密码
	userPass = u.String2Pass(userPass)
	sql := fmt.Sprintf("select `id`,`name`,`pass`,`nicename`,`email`,`face_img`,`status`,`description`,`add_time`,`update_time` "+
		"from bg_user where name='%s' and pass='%s'", userName, userPass)

	err = Db.QueryRow(sql).Scan(&u.Id, &u.Name, &u.Pass, &u.NiceName, &u.Email, &u.FaceImg, &u.Status, &u.Description, &u.AddTime, &u.UpdateTime)
	if err != nil {
		err = errors.New("用户名或密码错误")
		return
	}

	return
}

//根据Id获取用户信息
func (u *AdminUser) Info() (err error) {
	id := u.Id
	if id < 1 {
		return errors.New("用户ID错误")
	}
	sql := fmt.Sprintf("select `id`,`name`,`pass`,`nicename`,`email`,`face_img`,`status`,`description`,`add_time`,`update_time` "+
		"from bg_user where id=%d", id)

	err = Db.QueryRow(sql).Scan(&u.Id, &u.Name, &u.Pass, &u.NiceName, &u.Email, &u.FaceImg, &u.Status, &u.Description, &u.AddTime, &u.UpdateTime)
	if err != nil {
		err = errors.New("未查询到该用户")
	}

	if u.Status == -1 {
		err = errors.New("该用户已经被禁用")
	}

	return
}

//更新信息
func (u *AdminUser) Update(d AdminUser) (err error) {
	id := u.Id
	if id < 1 {
		return errors.New("用户ID错误")
	}

	sql := fmt.Sprintf("update `bg_user` set name='%s', pass='%s', nicename='%s', email='%s',phone='%s' ,face_img='%s', status=%d, description='%s' where id=%d",
		d.Name, d.Pass, d.NiceName, d.Email, d.Phone, d.FaceImg, d.Status, d.Description, id)

	res, err := Db.Exec(sql)
	if err != nil {
		return
	}
	if num, err := res.RowsAffected(); num == 0 || err != nil {
		return errors.New("update error")
	}

	return
}

//列表
func (u *AdminUser) Lists() (lists map[int64]AdminUser, err error) {

	return
}

//删除
func (u *AdminUser) Delete() (err error) {
	id := u.Id
	if id < 1 {
		return errors.New("用户ID错误")
	}

	return
}

//字符串转密码
func (u *AdminUser) String2Pass(str string) string {
	return Md5(str + "|" + RunCFG.UserPassExt)
}
